# -*- coding: UTF-8 -*-
"""
@author: tgy
@file: demo01.py
@time: 2022/02/11
"""

import http.client
import hashlib
import urllib
import random
import json

appid = '20220211001080566'
secretKey = 'zPrj0ud9ZyIAjQw461su'

httpClient = None
myurl = '/api/trans/vip/fieldtranslate'

def translate():
    fromLang = 'auto'
    toLang = 'zh'
    salt = random.randint(32768, 65536)
    q = 'apple'
    domain = 'medicine'
    sign = appid + q + str(salt) + domain + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    last_url = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
        q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&domain=' + domain + '&sign=' + sign

    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', last_url)

        # response
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)

        print(result)

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()

if __name__ == '__main__':
    pass
    translate()